import { ElMessage, ElMessageBox } from "element-plus";
import { ErrorCode, type R } from "@/types";

type Api = () => Promise<R<any>>;

/**
 * 通用的删除处理hook
 * 提示是否删除，删除成功后提示。
 * 非SUCCESS则提示msg
 * @param api {@link Api} 删除接口
 * @param message 删除前确认框的提示信息
 */
export function useDelete(api: Api, message: string = "确认要删除吗?"): Promise<boolean> {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(message, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        api().then((res: R<any>) => {
          if (res.code === ErrorCode.Success) {
            ElMessage({
              message: res.message,
              type: "success"
            });
            resolve(true);
          } else {
            reject(false);
          }
        });
      })
      .catch(() => {
        reject(false);
      });
  });
}
